package org.raymond.iworks.study.netty.atguigu.netty.sticky;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class StickyServer {
    public static void main(String[] args) throws Exception {
        int port = 6666;
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(2);
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workGroup)
                    .option(ChannelOption.SO_BACKLOG, 128) // tcp/ip协议,listen函数中的backlog参数,用来初始化服务端可连接队列
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持连接
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // maxFrameLength: 收到报文的最大长度
                                    // lengthFieldOffset: 长度域偏移量,指的是长度域位于整个数据包字节数组中的下标
                                    // lengthFieldLength: 长度域的自己的字节数长度
                                    // lengthAdjustment: 长度域的偏移量矫正.
                                    // 如果长度域的值,除了包含有效数据域的长度外,还包含了其他域(如长度域自身)长度,那么,就需要进行矫正.
                                    // 矫正的值为:包长 - 长度域的值 – 长度域偏移 – 长度域长
                                    // initialBytesToStrip: 丢弃的起始字节数.丢弃处于有效数据前面的字节数量.
                                    // 比如前面有4个节点的长度域,则它的值为4.
                                    .addLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                    .addLast(new StickyServerHandler());
                        }
                    });
            // 绑定并启动
            ChannelFuture future = sb.bind(port).sync();
            future.addListener(f -> {
                if(f.isSuccess()){
                    log.info("监听端口 {} 成功", port);
                }else{
                    log.info("监听端口 {} 失败", port);
                }
            });
            // 对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
